package com.hyfrogx.modules.manage.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.param.ErrorCode;
import com.hyfrogx.common.param.JSONResult;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.manage.entity.HyUserLog;
import com.hyfrogx.modules.manage.entity.permission.Permission;
import com.hyfrogx.modules.manage.entity.role.permission.RolePermission;
import com.hyfrogx.modules.manage.service.HyUserLogService;
import com.hyfrogx.modules.manage.service.PermissionService;
import com.hyfrogx.modules.manage.service.RolePermissionService;
import com.hyfrogx.modules.sys.form.UserPassUpdateForm;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

@Log4j
@RestController
@RequestMapping("/hyuser")
@Api(value = "会员用户controller", tags = {"后台-会员用户管理"})
public class HyUserController extends BaseController {


    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private HyUserLogService hyUserLogService;


    @PostMapping("/list")
    public JSONResult getVodUpList(@RequestBody Map<String,Object> params) {
        return ajaxSuccess(userService.selectPageByConditions(new QueryExt(params)));
    }

/*    *//**
     * 用户信息及权限列表
     */
    /*@GetMapping("/{uid}/rolePermission")
    public JSONResult getRolePermission(@PathVariable Integer uid) {
        User u =userService.getById(uid);
        if (u == null) {
            return ajaxFail("用户不存在");
        }
        List<RolePermission> list=rolePermissionService.getBaseMapper().selectList(new QueryWrapper<RolePermission>().eq("role_id",u.getRid()));
        List<Integer>  pIds=new ArrayList<Integer>();
        if(ObjectUtil.isNotNull(list)){
            list.forEach(rolePermission -> pIds.add(rolePermission.getPermissionId()));
        }
        if(pIds.size()>0){
            return ajaxSuccess(permissionService.getBaseMapper().selectList(new QueryWrapper<Permission>().in("pid",pIds)));
        }else{
            return ajaxFail("用户无任何权限");
        }
    }*/


    /**
     * 用户详情
     */
    @GetMapping("/{uid}/detail")
    public JSONResult getDetail(@PathVariable Integer uid) {
        return ajaxSuccess(userService.getBaseMapper().selectById(uid));
    }

    /**
     * 更新后台用户头像
     * @param file
     * @return
     */
    @PostMapping("/{uid}/updateImg")
    public JSONResult updateImg(@PathVariable Integer uid,MultipartFile file) {
        try {
            if (file == null) {
                return ajaxFail("请选择上传图片!");
            }

            User user=userService.getBaseMapper().selectById(uid);

            String url=userService.updateUserImg(file);
            // 修改后,查询该用户新的头像和昵称
            if(ObjectUtil.isNull(url)){
                return ajaxFail("上传文件失败");
            }

            user.setUpdateTime(new Date());
            user.setHead(url);
            userService.getBaseMapper().updateById(user);
            return ajaxSuccess(url);
//            User u = userService.getUsersById(uid);
//            Tim tim = new Tim();
//            if (u.getHead() != null) {
//                // 设置头像及昵称
//                tim.setIdentifier(u.getToken());
//                tim.setNick(u.getUsername());
//                tim.setFaceUrl(ImUtils.faceUrl + u.getHead());
//            } else {
//                tim.setFaceUrl("http://118.89.246.194:8080/img/live/14632031-177e-4930-9f56-8da4ba02de93.png");
//            }
//            int code = ImController.updateUserInfo(tim);
//            if (code == 0) {
//                return ajaxSuccess(u.getHead());
//            } else {
//                return ajaxFail("Im资料同步失败");
//            }
        } catch (Exception e) {
            return ajaxFail(e.getMessage());
        }
    }


    // 创建用户
    @PostMapping(value = "/create")
    public JSONResult create(@Valid User user) {

        // 校验账号唯一
        User u=userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("account",user.getAccount()));
        if (ObjectUtil.isNotNull(u)) {
            return ajaxFail("账号已存在,请重新输入");
        }

        User us = userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("phone",user.getAccount()));
        if (ObjectUtil.isNotNull(us)) {
            return ajaxFail("手机号已存在,请重新输入");
        }

//        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
//            Role role = roleService.findById(user.getRid());
//            user.setRole(role);
//            if (loginUser.getRole().getGrade() <= role.getGrade()) {
//                return ajaxFail("不能创建权限等级比自己高的角色");
//            }
        if(ObjectUtil.isNull(user.getPassword())){
            String password = SecureUtil.md5("123456" + user.getPhone().substring(0, 5));
            user.setPassword(password);
        }else{
            user.setPassword(user.getPassword());
        }
        user.setStatus(FrogConstant.UserStatus.NORMAL);
        user.setCreated(new Date());
        userService.getBaseMapper().insert(user);
        return ajaxSuccess();
    }



    /**
     * 更新用户
     */
    @RequestMapping(value = "/edit")
    public JSONResult post(@Valid User user) {

        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        // 是否有编辑角色的权限
        if (!SecurityUtils.getSubject().isPermitted("user:roleEdit")) {
            return ajaxFail("您没有修改角色的权限");
        }
        userService.getBaseMapper().updateById(user);

        HyUserLog hyUserLog = new HyUserLog();
        hyUserLog.setUid(loginUser.getUid());
        hyUserLog.setDealtime(new Date());
        hyUserLog.setType(1);
        hyUserLog.setRemark("后台管理员修改了用户个人信息.");
        hyUserLogService.getBaseMapper().insert(hyUserLog);

//        userService.updateSelective(user);
//            // 修改后,查询该用户新的头像和昵称
//            User u = userService.getUsersById(user.getUid());
//            // 修改信息日志记录
//            HyUserLog hyUserLog = new HyUserLog();
//            hyUserLog.setUid(u.getUid());
//            hyUserLog.setDealtime(new Date());
//            hyUserLog.setType(1);
//            hyUserLog.setRemark("后台管理员修改了用户个人信息。修改后为：" + u.toString());
//            userLogService.createUserLog(hyUserLog);
//
//            // 如果是禁用用户,发送推送
//            if (user.getStatus() != null && user.getStatus() == 0) {
//                AppPush appPush = new AppPush();
//                // 点击"通知"的后续行为，默认为打开app
//                appPush.setAfterOpen(1);
//                appPush.setTitle("您的账号已被禁用");
//                appPush.setText("您的账号已被禁用，有问题请联系客服");
//                appPush.setTicker("请注意");
//                appPush.setType(AppPushParam.AppPushType.current);
//                appPush.setUid(user.getUid());
//                // 推送范围，0全部，1个体
//                appPush.setDisplayRange(1);
//                // 推送渠道：ios/andriod
//                appPush.setDisplayChannel(2);
//                appPush.setCustomAfterOpen(9);
//                umengService.singleBroadcastByBan(appPush);
//            }
        return ajaxSuccess();
    }


    /**
     * 修改密码
     * @param form
     */
    @PostMapping(value = "/updatePass")
    public JSONResult updatePass(UserPassUpdateForm form) {

        // 先判断登录用户的账号密码是否一致
        if (form.getOldPassword()== null) {
            return ajaxFail("请传入旧密码");
        }
        User targetUser = userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("uid",form.getUid()).eq("password",SecureUtil.md5(form.getOldPassword())));
        if (null == targetUser) {
            return ajaxFail(ErrorCode.ERROR_ACCOUNT);
        }
        User users = new User();
        users.setUid(form.getUid());
        users.setPassword(SecureUtil.md5(form.getNewPassword()));
        userService.getBaseMapper().updateById(users);
        return ajaxSuccess();
    }




}
